﻿using System.ComponentModel;
using System.Reflection;

namespace Pay.DTO
{
	/// <summary>
	/// 枚举扩展
	/// </summary>
	public static class EnumExtensions
	{
		/// <summary>
		/// 获取枚举描述
		/// </summary>
		public static string ToDescription(this System.Enum value)
		{
			var type = value.GetType();
			var name = System.Enum.GetName(type, value);
			if (string.IsNullOrWhiteSpace(name))
			{
				return value.ToString();
			}

			var field = type.GetField(name);
			var description = field?.GetCustomAttribute<DescriptionAttribute>();
			return description == null ? value.ToString() : description.Description;
		}

		/// <summary>
		/// 获取枚举类型所有值描述
		/// </summary>
		public static List<KeyValuePair<int, string>> ToAllValueDesc(this System.Type type)
		{
			var list = new List<KeyValuePair<int, string>>();
			if (!type.IsEnum)
				return list;
			var values = System.Enum.GetValues(type);
			if (values.Length > 0)
			{
				foreach (var item in values)
				{
					list.Add(new KeyValuePair<int, string>((int)item, ((System.Enum)item).ToDescription()));
				}
			}

			return list;
		}
	}
}
